package com.cecsmsserve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cecsmsserve.entity.HealthRecord;
import com.cecsmsserve.mapper.HealthRecordMapper;
import com.cecsmsserve.service.HealthRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class HealthRecordServiceImpl extends ServiceImpl<HealthRecordMapper, HealthRecord> implements HealthRecordService {
    
    @Autowired
    private HealthRecordMapper healthRecordMapper;
    
    @Override
    public Page<HealthRecord> getRecordsByUserIdWithPage(Integer pageNum, Integer pageSize, Integer userId) {
        if (pageNum == null || pageSize == null || userId == null) {
            return null;
        }
        
        Page<HealthRecord> page = new Page<>(pageNum, pageSize);
        return healthRecordMapper.getRecordsByUserIdWithPage(page, userId);
    }
    
    @Override
    public boolean addRecord(HealthRecord healthRecord) {
        return save(healthRecord);
    }
    
    @Override
    public boolean updateRecord(HealthRecord healthRecord) {
        return updateById(healthRecord);
    }
    
    @Override
    public boolean deleteRecord(Integer id, Integer userId) {
        QueryWrapper<HealthRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id).eq("user_id", userId);
        return remove(wrapper);
    }
    
    @Override
    public HealthRecord getRecordDetailById(Integer id) {
        return getById(id);
    }
    
    @Override
    public List<HealthRecord> getRecordsByTypeAndDateRange(Integer userId, Integer typeId, LocalDate startDate, LocalDate endDate) {
        return healthRecordMapper.getRecordsByTypeAndDateRange(userId, typeId, startDate, endDate);
    }
    
    @Override
    public List<Map<String, Object>> getTypeStatistics(Integer userId, LocalDate startDate, LocalDate endDate) {
        return healthRecordMapper.getTypeStatistics(userId, startDate, endDate);
    }
    
    @Override
    public Integer checkExistingRecord(Integer userId, Integer typeId, LocalDate recordDate) {
        return healthRecordMapper.countByUserIdAndTypeIdAndDate(userId, typeId, recordDate);
    }
} 